/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.chart.Chart.CHART_URL = '../../../ext3/resources/charts.swf';
Ext.QuickTips.init();
var _pageSize = 20;
var store;
var now = new Date();
var defaultMonth = now;
var saveServlet = '../../../servlet/data/YsjSave';
var loadServlet = '../../../servlet/data/YsjLoad';

var fieldName = ['name', 'shortName', 'pointType', 'pointType2', 'dataTime', 'voltageLevelName', 'maxVoltage', 'maxVoltageTime', 'minVoltage', 'minVoltageTime', 'avgVoltage',
    'defaultTotalTime', 'aboveUpperLimitMin', 'aboveUpperLimitNumber', 'underLowerLimitMin', 'underLowerLimitNumber', 'totalRunMin', 'rate', 'dataYear', 'dataMonth', 'dataDay',
    'id', 'isOffline', 'deviceId', 'pointId', 'type', 'status', 'reasonAnalyze', 'treatWay', 'completeCase', 'note', 'did', 'lowerLimit', 'upperLimit', 'voltageLevelValue'
    ,"reportStatusCh","orgCode","company","subCompany","pointArea","pointPosition","pointTypeId","pointType2Id","lowerLimit","upperLimit","orgTypeId",
    "orgTypeName","voltage","voltageLevelValue","voltageLevelId","voltageLevelName","startStatus","reportStatus",'code','companyCode'];
var fieldLabel = ['测点名称', '单位名称', '测点类别', '电网类别', '日期', '电压等级<br/>(kv)', '最高电压',
    '最高电压时间', '最低电压', '最低电压时间', '平均电压', '故障时间<br/>（分钟）',
    "超上限时间<br/>（分钟）", "超上限<br/>次数", "超下限时间<br/>（分钟）", "超下限<br/>次数", '总时间<br/>（分钟）', '合格率（%）', '年', '月', '日', 'ID', '在线离线', '设备ID', '监测点ID',
    '类型', '状态', '原因分析', '处理', '完成情况', '备注'];

var theme = '月数据';

var mergeProperties = function(o, n, override) {
    for (var p in n)
        if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override))
            o[p] = n[p];
};

var basic11 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '测点名称',
            name: 'name',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '单位名称',
            name: 'shortName',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'numberfield',
            fieldLabel: '电压上限',
            name: 'upperLimit',
            anchor: '95%',
            format: '0.000',
            readOnly: true
        }
    ]
};

var basic12 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '测点类别',
            name: 'pointType',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '电网类别',
            name: 'pointType2',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'numberfield',
            fieldLabel: '电压下限',
            name: 'lowerLimit',
            format: '0.000',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic13 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '电压等级(kv)',
            name: 'voltageLevelName',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '日期',
            id: 'DataYearMonth',
            name: 'dataYearMonth',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'numberfield',
            fieldLabel: '额定电压',
            name: 'voltageLevelValue',
            format: '0.000',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic1 = {
    xtype: 'fieldset',
    title: '基本信息',
    id: 'Basic1',
    autoHeight: true,
    layout: 'column',
    items: [basic11, basic12, basic13]
};


var basic21 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '最高电压',
            name: 'maxVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '最低电压',
            name: 'minVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '平均电压',
            name: 'avgVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '故障时间',
            name: 'defaultTotalTime',
            anchor: '95%',
            hidden: true
        },
        {
            xtype: 'numberfield',
            fieldLabel: '总时间',
            id: 'TotalRunMin',
            name: 'totalRunMin',
            format: '0.000',
            anchor: '95%',
            listeners: {
                blur: function(o) {
                    //alert(typeof o.getValue());
                    //alert(o.getValue());
                    //alert(Ext.getCmp('UnderLowerLimitMin').getValue());
                    //alert((o.getValue()-(Ext.getCmp('UnderLowerLimitMin').getValue()+Ext.getCmp('AboveUpperLimitMin').getValue()))/o.getValue()*100);
                    //Ext.getCmp('Rate').setValue((o.getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / o.getValue() * 100);
                    var rate = (Ext.getCmp('TotalRunMin').getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / Ext.getCmp('TotalRunMin').getValue() * 100;
                    rate = rate.toFixed(3);
                    Ext.getCmp('Rate').setValue(rate);
                }
            }
        }
    ]
};

var basic22 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'datefield',
            fieldLabel: '最高电压日期',
            id: 'MaxVoltageDate',
            name: 'maxVoltageDate',
            format: 'Y-m-d',
            anchor: '95%'
        },
        {
            xtype: 'datefield',
            fieldLabel: '最低电压日期',
            id: 'MinVoltageDate',
            name: 'minVoltageDate',
            format: 'Y-m-d',
            anchor: '95%'
        },
        {
            xtype: 'numberfield',
            fieldLabel: '超上限时间',
            id: 'AboveUpperLimitMin',
            name: 'aboveUpperLimitMin',
            anchor: '95%',
            listeners: {
                blur: function(o) {
                    //alert(typeof o.getValue());
                    //alert(o.getValue());
                    //alert(Ext.getCmp('UnderLowerLimitMin').getValue());
                    //alert((o.getValue()-(Ext.getCmp('UnderLowerLimitMin').getValue()+Ext.getCmp('AboveUpperLimitMin').getValue()))/o.getValue()*100);
                    var rate = (Ext.getCmp('TotalRunMin').getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / Ext.getCmp('TotalRunMin').getValue() * 100;
                    rate = rate.toFixed(3);
                    Ext.getCmp('Rate').setValue(rate);
                }
            }
        },
        {
            xtype: 'textfield',
            fieldLabel: '超上限次数',
            name: 'aboveUpperLimitNumber',
            anchor: '95%',
            hidden: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '合格率（%）',
            id: 'Rate',
            format: '0.000',
            name: 'rate',
            anchor: '95%'
        }
    ]
};

var basic23 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'timefield',
            fieldLabel: '最高电压时间',
            id: 'MaxVoltageTime',
            name: 'maxVoltageTime',
            format: 'H:i:s',
            anchor: '95%'
        },
        {
            xtype: 'timefield',
            fieldLabel: '最低电压时间',
            id: 'MinVoltageTime',
            name: 'minVoltageTime',
            format: 'H:i:s',
            anchor: '95%'
        },
        {
            xtype: 'numberfield',
            fieldLabel: '超下限时间',
            id: 'UnderLowerLimitMin',
            name: 'underLowerLimitMin',
            anchor: '95%',
            listeners: {
                blur: function(o) {                   
                    var rate = (Ext.getCmp('TotalRunMin').getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / Ext.getCmp('TotalRunMin').getValue() * 100;
                    rate = rate.toFixed(3);
                    Ext.getCmp('Rate').setValue(rate);
                }
            }
        },
        {
            xtype: 'textfield',
            fieldLabel: '超下限次数',
            name: 'underLowerLimitNumber',
            anchor: '95%',
            hidden: true
        }
    ]
};

var basic2 = {
    xtype: 'fieldset',
    title: '数据信息',
    id: 'Basic2',
    autoHeight: true,
    layout: 'column',
    items: [basic21, basic22, basic23]
};

var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [
                basic1, basic2
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {lock: lock}
                        };

                        var did = checkboxSel.getSelected().get('did');
                        var pointId = checkboxSel.getSelected().get('id');
                        var deviceId = checkboxSel.getSelected().get('deviceId');
                        var dataYear = Ext.getCmp('DateFrom').getValue().format('Y');
                        var dataMonth = Ext.getCmp('DateFrom').getValue().format('m');

                        submitConfig.params.pointId = pointId;
                        submitConfig.params.deviceId = deviceId;
                        submitConfig.params.dataYear = dataYear;
                        submitConfig.params.dataMonth = dataMonth;

                        if (did === null || did === '') {
                            var r = checkboxSel.getSelected();
                            var orgCode = r.get("orgCode");
                            var company = r.get("company");
                            var subCompany = r.get("subCompany");
                            var station = r.get("shortName");
                            var name = r.get("name");
                            var pointArea = r.get("pointArea");
                            var pointPosition = r.get("pointPosition");
                            var pointTypeId = r.get("pointTypeId");
                            var pointType  = r.get("pointType");
                            var pointType2Id = r.get("pointType2Id");
                            var pointType2  = r.get("pointType2");
                            var lowerLimit = r.get("lowerLimit");
                            var upperLimit = r.get("upperLimit");
                            var startStatus = r.get("startStatus");
                            var reportStatus = r.get("reportStatus");
                            var orgTypeId = r.get("orgTypeId");
                            var orgTypeName = r.get("orgTypeName");
                            var voltage = r.get("voltage");
                            var voltageLevelValue = r.get("voltageLevelValue")
                            var voltageLevelId = r.get("voltageLevelId");
                            var voltageLevelName = r.get("voltageLevelName");
                            var pointCode = r.get("code");
                            var companyCode = r.get("companyCode");
                            submitConfig.params.orgCode = orgCode;
                            submitConfig.params.company = company;
                            submitConfig.params.subCompany = subCompany;
                            submitConfig.params.station = station;
                            submitConfig.params.name = name;
                            submitConfig.params.pointArea = pointArea;
                            submitConfig.params.pointPosition = pointPosition;
                            submitConfig.params.pointTypeId  = pointTypeId;
                            submitConfig.params.pointType = pointType;
                            submitConfig.params.pointType2Id = pointType2Id;
                            submitConfig.params.pointType2 = pointType2;
                            submitConfig.params.lowerLimit = lowerLimit;
                            submitConfig.params.upperLimit = upperLimit;
                            submitConfig.params.startStatus = startStatus;
                            submitConfig.params.reportStatus = reportStatus;
                            submitConfig.params.orgTypeId = orgTypeId;
                            submitConfig.params.orgTypeName = orgTypeName;
                            submitConfig.params.voltage = voltage;
                            submitConfig.params.voltageLevelValue = voltageLevelValue;
                            submitConfig.params.voltageLevelId = voltageLevelId;
                            submitConfig.params.voltageLevelName = voltageLevelName;                           
                            submitConfig.params.pointCode = pointCode;
                            submitConfig.params.companyCode = companyCode;
                            submitConfig.params.cmd = 'createLock';
                            
                        }
                        else {
                            submitConfig.params.id = did;
                            submitConfig.params.cmd = 'updateLock';
                        }
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        Ext.getCmp('input-form').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);

var win = new Ext.Window({
    layout: 'form',
    width: 700,
    modal: true,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});


var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;



function copyRawData() {
    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }

    if (currentOrgCode.length !== 4) {
        Ext.Msg.alert("系统提示", "只允许市级公司进行操作");
        return;
    }
    
      Ext.MessageBox.confirm('提示', '该操作会删除锁定表中已经修改好的数据。</br>确实要拷贝原始月数据到锁定表吗?', function(btn) {
        if (btn !== "yes")
            return;

        var date = Ext.getCmp('DateFrom').getValue().format('Ym');

        var reportStatus = -1;
        var range = -1;
        var token1 = new Date().getTime();
        Ext.Ajax.request({
            url: '../../../servlet/data/LockServlet',
            success: function(response, options) {
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                    Ext.Msg.alert("系统提示", "获取原始数据成功");
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
            },
            failure: function(response, opts) {
                Ext.Msg.alert('系统提示', '获取原始数据失败，清稍候再试 ' + response.status);
            },
            params: {token:token,token1:token1,lock: lock, cmd: "copyYOrg", date: date, reportStatus: reportStatus, range: range}
        });
    });
}

function manualRecall() {

    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                modal: true,
                closeAction: 'hide',
                items: [inputForm]
            });
        }
        type = 2;
        var record = checkboxSel.getSelected();
        var dataYear = record.get("dataYear");



        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());


        Ext.getCmp('DataYearMonth').setValue(Ext.getCmp('DateFrom').getValue().format('Y年m月'));

        var maxTime = record.get('maxVoltageTime');
        var minTime = record.get('minVoltageTime');

        var maxVoltageDate = Date.parseDate(maxTime, "Y-m-d H:i:s.u");
        var minVoltageDate = Date.parseDate(minTime, "Y-m-d H:i:s.u");
        Ext.getCmp("MaxVoltageDate").setValue(maxVoltageDate);
        Ext.getCmp("MinVoltageDate").setValue(minVoltageDate);

        Ext.getCmp("MaxVoltageTime").setValue(maxTime.substring(11, 19));
        Ext.getCmp("MinVoltageTime").setValue(minTime.substring(11, 19));

        var rate = record.get('rate');
        var rateFloat = parseFloat(rate);
        Ext.getCmp("Rate").setValue(rateFloat.toFixed(3));

        if (dataYear === null || dataYear === '') {
            Ext.getCmp("MaxVoltageDate").setValue(Ext.getCmp('DateFrom').getValue());
            Ext.getCmp("MinVoltageDate").setValue(Ext.getCmp('DateFrom').getValue());
        }

        win.setTitle('人工录入' + theme);
        win.show();
    }
}

var excelForm = new Ext.FormPanel({
    //renderTo: 'fi-form',
    fileUpload: true,
    width: 500,
    frame: true,
    autoHeight: true,
    bodyStyle: 'padding: 10px 10px 0 10px;',
    labelWidth: 80,
    defaults: {
        anchor: '95%',
        allowBlank: false,
        msgTarget: 'side'
    },
    items: [
        {
            xtype: 'datefield',
            format: 'Y-m',
            id: "UploadDate",
            name: 'date',
            fieldLabel: '数据年月'

        },
        {
            xtype: 'fileuploadfield',
            id: 'form-file',
            emptyText: '请选择月数据Excel文件',
            fieldLabel: '月数据文件',
            name: 'path',
            buttonText: '...',
            buttonCfg: {
                iconCls: 'upload-icon'
            }
        }],
    buttons: [{
            text: '上传导入',
            handler: function() {
                if (excelForm.getForm().isValid()) {
                    excelForm.getForm().submit({
                        url: '../../../servlet/common/UploadImportExcelServlet',
                        waitMsg: '正在上传Excel文件...',
                        success: function(excelForm, action) {
                            //Ext.Msg.alert('系统提示', '导入成功');
                            Ext.Msg.alert('系统提示', action.result.msg);
                        },
                        failure: function(form, action) {
                            switch (action.failureType) {
                                case Ext.form.Action.CONNECT_FAILURE:
                                    Ext.Msg.alert('提示', '网络连接失败');
                                    break;
                                case Ext.form.Action.SERVER_INVALID:
                                    Ext.Msg.alert('提示', action.result.msg);
                                default:
                                    Ext.Msg.alert('提示', action.result.msg);
                            }
                        },
                        params: {lock: lock}
                    });
                }
            }
        }, {
            text: '重置',
            handler: function() {
                excelForm.getForm().reset();
            }
        }]
});

var winExcel = new Ext.Window({
    title: '选择要导入的月数据excel文件',
    layout: 'form',
    modal: true,
    //width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [excelForm]
});

function excelImport() {
    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    Ext.getCmp("UploadDate").setValue(Ext.getCmp('DateFrom').getValue());
    winExcel.show();

}

function batchCreate() {
    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    Ext.MessageBox.confirm('提示', '该操作将生产当前搜索条件下所有缺失数据。</br>确实要生成无数据监测点的月数据吗?', function(btn) {
        if (btn !== "yes")
            return;

        var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
        myMask.show();
        var token1 = new Date().getTime();
        var params = {cmd: "batchCreateLock", have: 1,token:token,token1:token1};
        mergeProperties(params, store.baseParams);
        
        Ext.Ajax.request({
            url: saveServlet,
            //timeout: 50000,
            success: function(response, options) {
                //alert(response.responseText);
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
                myMask.hide();
            },
            failure: function(response, opts) {
                Ext.Msg.alert('系统提示', '生成失败，清稍候再试 ' + response.status);
                myMask.hide();
            },
            params: params
        });
    });
}

function manualRemove() {
    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能清除");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行清除");
    }
    else {

        var pointId = checkboxSel.getSelected().get("pointId");
        var dataYear = checkboxSel.getSelected().get("dataYear");
        var dataMonth = checkboxSel.getSelected().get("dataMonth");

        if (dataYear === null || dataYear === '') {
            Ext.Msg.alert("系统提示", "该监测点无数据");
            return;
        }


        Ext.MessageBox.confirm('提示', '确实要清除所选记录的数据吗?', function(btn) {
            if (btn !== "yes")
                return;

            var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
            myMask.show();
            var token1 = new Date().getTime();
            Ext.Ajax.request({
                url: saveServlet,
                //timeout: 50000,
                success: function(response, options) {
                    //alert(response.responseText);
                    var obj = Ext.decode(response.responseText);
                    if (obj.success) {
                        store.reload();
                    } else {
                        Ext.Msg.alert("系统提示", obj.msg);
                    }
                    myMask.hide();
                },
                failure: function(response, opts) {
                    Ext.Msg.alert('系统提示', '删除失败，清稍候再试 ' + response.status);
                    myMask.hide();
                },
                params: {token:token,token1:token1,lock: lock, cmd: "remove", pointId: pointId, dataYear: dataYear, dataMonth: dataMonth}
            });
        });
    }
}

function removeAll() {

    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    Ext.MessageBox.confirm('提示', '<font color="#ff0000">确实要清除所有记录的数据吗?<br/>清除后将不可恢复，请谨慎操作！！！</font>', function(btn) {
        if (btn !== "yes")
            return;

        var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
        myMask.show();
        var token1 = new Date().getTime();
        var params = {token:token,token1:token1,lock: lock, cmd: "removeAll"};
        mergeProperties(params, store.baseParams);
        Ext.Ajax.request({
            url: saveServlet,
            //timeout: 50000,
            success: function(response, options) {
                //alert(response.responseText);
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
                myMask.hide();
            },
            failure: function(response, opts) {
                Ext.Msg.alert('系统提示', '删除失败，清稍候再试 ' + response.status);
                myMask.hide();
            },
            params: params
        });
    });
}

function lockData() {
    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length !== 4) {
        Ext.Msg.alert("系统提示", "只允许市级公司锁定数据");
        return;
    }

    Ext.MessageBox.confirm('系统提示', '锁定数据后将禁止修改数据。</br>确实要锁定数据吗?', function(btn) {
        if (btn !== "yes")
            return;

        var date = Ext.getCmp('DateFrom').getValue().format('Ym');

        var reportStatus = 1;
        var range = -1;
        var token1 = new Date().getTime();
        Ext.Ajax.request({
            url: '../../../servlet/data/LockServlet',
            success: function(response, options) {
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                    Ext.Msg.alert("系统提示", "锁定成功");
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
            },
            failure: function(response, opts) {
                Ext.Msg.alert('系统提示', '锁定失败，清稍候再试 ' + response.status);
            },
            params: {token:token,token1:token1,cmd: "lockYOrg", date: date, reportStatus: reportStatus, range: range}
        });
    });

}

function unlockData() {
    if (currentOrgCode.length !== 4) {
        Ext.Msg.alert("系统提示", "只允许市级公司锁定数据");
        return;
    }
    Ext.MessageBox.confirm('系统提示', '解锁后将可以修改数据。</br>确实要解锁吗?', function(btn) {
        if (btn !== "yes")
            return;

        var date = Ext.getCmp('DateFrom').getValue().format('Ym');

        var reportStatus = 1;
        var range = -1;
        var token1 = new Date().getTime();
        Ext.Ajax.request({
            url: '../../../servlet/data/LockServlet',
            success: function(response, options) {
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                    Ext.Msg.alert("系统提示", "解锁成功");
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
            },
            failure: function(response, opts) {
                Ext.Msg.alert('系统提示', '解锁失败，清稍候再试 ' + response.status);
            },
            params: {token:token,token1:token1,cmd: "unlockYOrg", date: date, reportStatus: reportStatus, range: range}
        });
    });
}


var recallForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RecallForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskSave',
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesRecall',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    disable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winRecall.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {lock: lock, cmd: 'createYBackflowTask'}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.dates = beginDate;
                        Ext.getCmp('RecallForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winRecall.hide();
                    }
                }]
        }
);

var winRecall = new Ext.Window({
    title: '数据回灌',
    layout: 'form',
    modal: true,
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [recallForm]
});

function backflow() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，请选择需要补采的监测点");
    } else {
        //var r = checkboxSel.getSelected();
        var pointNames = getFields(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesRecall').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        winRecall.show();
    }
}

var recallBatchForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RecallBatchForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskSave',
            items: [
                {
                    xtype: 'datefield',
                    fieldLabel: '数据时间',
                    id: 'DataTimeF',
                    name: 'dataTime',
                    format: 'Y年m月',
                    readOnly: true,
                    //value: now.add(Date.MONTH, -1),
                    anchor: '95%'
                }, new tlf.component.PointTypeCombo({value: -1})
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winRecall.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {lock: lock, cmd: 'createYBatchBackflowTask'}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.dateTo = Ext.getCmp('DataTimeF').getValue().format('Ym');
                        Ext.getCmp('RecallBatchForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winRecallBatch.hide();
                    }
                }]
        }
);

var winRecallBatch = new Ext.Window({
    title: '批量数据回灌',
    layout: 'form',
    width: 400,
    modal: true,
    autoHeight: true,
    closeAction: 'hide',
    items: [recallBatchForm]
});

function backflowBatch() {
    Ext.getCmp('DataTimeF').setValue(Ext.getCmp('DateFrom').getValue());
    winRecallBatch.show();

}

function downloadTemplate() {
    store.baseParams.type = 14;
    var encodeParams = Ext.urlEncode(store.baseParams);
    open('../../../servlet/common/ExcelFileCreate?' + encodeParams);
}

var rateSetForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RateSetForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/data/YsjSave',
            items: [
                {
                    xtype: 'label',
                    fieldLabel: '提示',
                    //height:'',
                    text: '该操作将调整合格率至指定值附近（只调整搜索条件下的所有监测点）'
                },
                {
                    xtype: 'datefield',
                    fieldLabel: '数据时间',
                    id: 'DataTime',
                    name: 'dataTime',
                    format: 'Y年m月',
                    readOnly: true,
                    //value: now.add(Date.MONTH, -1),
                    anchor: '95%'
                },
                //new tlf.component.PointTypeCombo({value: -1}),
                {
                    xtype: 'numberfield',
                    fieldLabel: '合格率(%)',
                    id: 'RateSetField',
                    name: 'rate',
                    decimalPrecision: 4,
                    allowBlank: false,
                    blankText: '必须填写合格率',
                    maxValue: 100,
                    maxText: '合格率必须小于100%',
                    minValue: 0,
                    minText: '合格率必须大于0',
                    anchor: '95%'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var params = {lock: lock, cmd: 'yRateSet'};
                        mergeProperties(params, store.baseParams);
                        var submitConfig = {
                            success: function(form, action) {
                                winRateSet.hide();
                                store.reload();
                                //Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: params
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.dateTo = Ext.getCmp('DataTime').getValue().format('Ym');
                        Ext.getCmp('RateSetForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winRateSet.hide();
                    }
                }]
        }
);

var winRateSet = new Ext.Window({
    title: '设置合格率',
    layout: 'form',
    modal: true,
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [rateSetForm]
});

function rateSet() {
    if (isLocked) {
        Ext.Msg.alert("系统提示", "数据已经锁定");
        return;
    }
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    Ext.getCmp("DataTime").setValue(Ext.getCmp("DateFrom").getValue());
    winRateSet.show();
}

var beginDate = defaultMonth.format('Ym');
var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
var isLocked = true;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName,
        autoLoad: true,
        baseParams: {cmd: 'general', lock: lock, start: 0, limit: _pageSize, dateFrom: defaultMonth.format('Ym'), dateTo: defaultMonth.format('Ym')}
    });

    store.on("load", function(o, records, options) {
        isLocked = o.reader.jsonData.isLock;
        if (!o.reader.jsonData.isLock) {
            grid.setIconClass(null);
        } else {
            grid.setIconClass("icon-lock");
        }
    });

    tbarPoint = new Ext.Toolbar({
        items: [
            pointTypeCombo, pointType2Combo, voltageLevelCombo, reportCombo, haveCombo, rangeCombo
                    , pointText, searchButton
        ]
    });
    tbarPoint.insert(0, {
        xtype: 'datefield',
        id: 'DateFrom',
        format: 'Y年m月',
        width: 150,
        value: defaultMonth,
        listeners: {
            select: function(c, date) {
                beginDate = date.format('Ym');
                store.baseParams.dateFrom = beginDate;
                store.baseParams.dateTo = beginDate;
            }
        }
    }
    );

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            new Ext.grid.RowNumberer({width: 40, header: '序号'}),
            {header: 'PointId', dataIndex: 'pointId', hidden: true},
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0]},
            {header: fieldLabel[1], width: 80, sortable: true, dataIndex: fieldName[1]},
            {header: fieldLabel[2], width: 60, sortable: true, dataIndex: fieldName[2]},            
            {header: fieldLabel[3], width: 60, sortable: true, dataIndex: fieldName[3]},
            {header: '状态', width: 60, sortable: true, dataIndex: 'reportStatusCh'},
            {header: fieldLabel[5], width: 80, sortable: true, dataIndex: fieldName[5]},
            {header: '电压上限', width: 100, sortable: true, dataIndex: 'upperLimit', xtype: 'numbercolumn', format: '0.000', align: 'right'},
            {header: '电压下限', width: 100, sortable: true, dataIndex: 'lowerLimit', xtype: 'numbercolumn', format: '0.000', align: 'right'},
            {header: fieldLabel[17], width: 100, sortable: true, dataIndex: 'rate', align: 'right', format: '0.000'},
            {header: fieldLabel[6], width: 80, sortable: true, dataIndex: fieldName[6], xtype: 'numbercolumn', align: 'right'},
            {header: fieldLabel[7], width: 100, sortable: true, dataIndex: fieldName[7], xtype: 'datecolumn', format: 'Y-m-d H:i:s'},
            {header: fieldLabel[8], width: 80, sortable: true, dataIndex: fieldName[8], xtype: 'numbercolumn', align: 'right'},
            {header: fieldLabel[9], width: 100, sortable: true, dataIndex: fieldName[9], xtype: 'datecolumn', format: 'Y-m-d H:i:s'},
            {header: fieldLabel[10], width: 80, sortable: true, dataIndex: fieldName[10], align: 'right'},
            {header: fieldLabel[11], width: 80, sortable: true, dataIndex: fieldName[11], align: 'right'},
            {header: fieldLabel[12], width: 80, sortable: true, dataIndex: fieldName[12], align: 'right'},
            //{header: fieldLabel[13], width: 50, sortable: true, dataIndex: fieldName[13], align: 'right'},
            {header: fieldLabel[14], width: 80, sortable: true, dataIndex: fieldName[14], align: 'right'},
            //{header: fieldLabel[15], width: 50, sortable: true, dataIndex: fieldName[15], align: 'right'},
            {header: fieldLabel[16], width: 80, sortable: true, dataIndex: fieldName[16], align: 'right'},
            {header: '在线', width: 60, sortable: true, dataIndex: 'isOffline'},
        ],
        loadMask: true,
        tbar: new Ext.Toolbar([
            {
                text: '获取原始数据',
                iconCls: 'icon-linkratio',
                handler: copyRawData,
                hidden: lock === "" ?  true: false
            },
            {
                text: '手工录入',
                iconCls: 'icon-linkratio',
                handler: manualRecall
            }, {
                text: 'Excel导入',
                iconCls: 'icon-linkratio',
                handler: excelImport,
                hidden: lock === "" ? true : false
            }, {
                text: '缺失数据生成',
                iconCls: 'icon-linkratio',
                handler: batchCreate
            }, {
                text: '合格率设置',
                iconCls: 'icon-linkratio',
                handler: rateSet,
                hidden: lock === "" ? true : false
            }, {
                text: '月数据回灌',
                iconCls: 'icon-linkratio',
                handler: backflow,
                hidden: lock === "" ? true : false
            }, {
                text: '批量月数据回灌',
                iconCls: 'icon-linkratio',
                handler: backflowBatch,
                hidden: lock === "" ? true : false
            }, {
                text: '删除数据',
                iconCls: 'icon-linkratio',
                handler: manualRemove,
                hidden: !isSuper
            }, {
                text: '清除数据',
                iconCls: 'icon-removeAll',
                handler: removeAll,
                hidden: !isSuper
            }/*, {                              // 该处增加按钮 “拷贝原始数据”、“锁定”、“解锁”、“全部解锁”，“全部锁定”
             text: '拷贝原始数据', 
             iconCls: 'icon-linkratio',
             handler: removeAll,
             hidden: !isSuper
             }*/
            , {
                text: '锁定',
                iconCls: 'icon-lock',
                handler: lockData,
                hidden: lock === "" ? true : false
            },
            {
                text: '解锁',
                iconCls: 'icon-unlock',
                handler: unlockData,
                hidden: lock === "" ? true : false
            }
            , '->'
                    , {
                text: '下载模板',
                iconCls: 'icon-linkratio',
                handler: downloadTemplate,
                hidden: lock === "" ? true : false
            }
        ]),
        listeners: {
            'render': function() {
                tbarPoint.render(this.tbar);
            }
        },
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: '目前没有信息'
        })
    });

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });

}
Ext.onReady(buildWindow);
